package aiku.numericalcontroloa.common.utils;

import aiku.numericalcontroloa.project.system.pojo.entity.SysMenu;
import aiku.numericalcontroloa.project.system.pojo.vo.SysMenuVo;

import java.util.ArrayList;
import java.util.List;

public class SysMenuTreeUtil {
    private static final Integer TOP_NODE = -1;


    /**
     * menu转menuDto
     */
    public static List<SysMenuVo> convert(List<SysMenu> menus) {

        List<SysMenuVo> menuDtos = new ArrayList<>();
        menus.forEach(m -> {
            SysMenuVo dto = new SysMenuVo();
            dto.setId(m.getId());
            dto.setParentId(m.getParentId());
            dto.setName(m.getName());
            dto.setComponent(m.getComponent());
            dto.setIcon(m.getIcon());
            dto.setPath(m.getPath());
            dto.setHidden(m.getHidden());
            if (m.getChildren().size() > 0) {
                dto.setChildren(convert(m.getChildren()));
            }
            menuDtos.add(dto);
        });
        return menuDtos;
    }

    public static List<SysMenuVo> excludeTopNode(List<SysMenuVo> sysMenuVos) {
        List<SysMenuVo> objects = new ArrayList<>();
        if (sysMenuVos.size() == 0) {
            return objects;
        }
        List<SysMenuVo> children = sysMenuVos.get(0).getChildren();

        return children;
    }

    /**
     * 递归遍历
     *
     * @param list
     * @return
     */
    public static List<SysMenu> listToTree(List<SysMenu> list) {
        List<SysMenu> treeList = new ArrayList<>();
        for (SysMenu tree : list) {
            if (TOP_NODE.equals(tree.getParentId())) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    /**
     * 寻找子节点
     *
     * @param tree
     * @param list
     * @return
     */
    private static SysMenu findChildren(SysMenu tree, List<SysMenu> list) {
        for (SysMenu node : list) {
            if (node.getParentId().equals(tree.getId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<>());
                }
                List<SysMenu> ts = tree.getChildren();
                ts.add((findChildren(node, list)));
            }
        }
        return tree;
    }


}
